<template>
  <div class="page-curd">
    <curd-search @search="handleSearch"></curd-search>
    <div class="page-curd__action-bar">
      <el-button type="primary" icon="el-icon-plus" size="small" @click="handleNew">新增</el-button>
      <el-button icon="el-icon-delete" size="small"
                 :disabled="tableSelection && tableSelection.length <= 0"
                 @click="handleDeleteMul">批量删除
      </el-button>
    </div>
    <el-table size="mini" :data="tableData" class="page-curd__table" border
              @selection-change="handleTableSelectionChange">
      <el-table-column type="selection" min-width="35"></el-table-column>
      <el-table-column label="服务器名称" prop="serverName" min-width="100">
        <template slot-scope="{ row }"><span>{{ row.serverName }}</span></template>
      </el-table-column>
      <el-table-column label="ip" prop="serverIp">
        <template slot-scope="{ row }"><span>{{ row.serverIp }}</span></template>
      </el-table-column>
      <el-table-column label="服务器所有者" prop="serverOwner">
        <template slot-scope="{ row }"><span>{{ row.serverOwner }}</span></template>
      </el-table-column>
      <el-table-column label="监控地址" prop="clientMonitoringAddress">
        <template slot-scope="{ row }"><span>{{ row.clientMonitoringAddress }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="40" fixed="right">
        <template slot-scope="slotScope">
          <el-button class="eagle-scheme__table-btn" type="text" icon="el-icon-view" title="详情"
                     @click="handleView(slotScope)"></el-button>
          <el-button class="eagle-scheme__table-btn" type="text" icon="el-icon-edit" title="编辑"
                     @click="handleEdit(slotScope)"></el-button>
          <el-button type="text" icon="el-icon-delete" title="删除" @click="handleDelete(slotScope)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination class="page-curd__pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                   :current-page="currentPage"
                   :page-sizes="[10,20, 50, 100]"
                   :page-size="pageSize"
                   layout="total, sizes, prev, pager, next,jumper"
                   :total="total" background>
    </el-pagination>
    <el-dialog :visible.sync="dialogVisible" :title="title" width="450px" :close-on-click-modal="dialogMode === 'view'"
               append-to-body>
      <template v-if="dialogMode === 'view'">
        <el-row :gutter="20">
          <el-col :span="12">服务器名称：{{ formModel.serverName }}</el-col>
          <el-col :span="12">ip：{{ formModel.serverIp }}</el-col>
          <el-col :span="12">服务器所有者：{{ formModel.serverOwner }}</el-col>
          <el-col :span="12">监控地址：{{ formModel.clientMonitoringAddress }}</el-col>
        </el-row>
      </template>
      <template v-else>
        <curd-form ref="curdForm" v-model="formModel" @submit="handleSubmit" @cancel="handleCancel"></curd-form>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import CurdSearch from './search';
import CurdForm from './form';
import axios from 'axios';

export default {
  components: {CurdSearch, CurdForm},
  data: () => ({
    dialogMode: 'new',
    dialogVisible: false,
    tableData: [
      {id: "", serverName: "", serverIp: "", serverOwner: "", clientMonitoringAddress: ""}],
    currentPage: 1,
    pageSize: 10,
    total: 3,
    tableSelection: [],
    formModel: {}
  }),
  computed: {
    title() {
      if (this.dialogMode === 'view') {
        return '查看服务器';
      }
      return this.dialogMode === 'edit' ? '编辑服务器' : '新增服务器';
    }
  },
  created() {
    this.handleSearch({model:{}});
  },
  methods: {
    async handleSearch({model, needReset}) {
      if (needReset) {
        this.currentPage = 1;
      }
      var keyWord = "";
      if(model.keyword !== undefined){
        keyWord = model.keyword
      }
      axios.get('/resource/server-config/list?keyWord='+keyWord)
          .then(response => {
            if (response.data.code === 0) {
              this.tableData = response.data.data
              this.total = response.data.data.length;
            }
          })
          .catch(error => {
            console.log(error);
          });
    }, handleNew() {
      if (this.$refs['curdForm']) {
        this.$refs['curdForm'].reset();
      }
      this.dialogMode = 'new';
      this.dialogVisible = true;
      this.formModel = {};
    }, handleView({row}) {
      this.dialogMode = 'view';
      this.dialogVisible = true;
      this.formModel = {...row};
    }, handleEdit({row}) {
      if (this.$refs['curdForm']) {
        this.$refs['curdForm'].reset();
      }
      this.dialogMode = 'edit';
      this.dialogVisible = true;
      this.formModel = {...row};
      console.log(this.formModel);
    }, handleDelete({row}) {
      console.log('delete：', row);
      this.$confirm('确定要删除该配置?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = {"idList": [row.id]};
        axios.delete('/resource/server-config/delete', {data})
            .then(response => {
              if (response.data.code === 0) {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                this.$router.go(0); // 刷新页面
              }
            })
            .catch(error => {
              console.log(error);
            });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    }, handleDeleteMul() {
      console.log('mul delete：', this.tableSelection);
      this.$confirm('确定要删除选中配置?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let tableSelection = this.tableSelection;
        const idArr = [];
        tableSelection.forEach(function (item, index, self) {
          idArr.push(item.id);
        })
        const data = {"idList": idArr};
        axios.delete('/resource/server-config/delete', {data})
            .then(response => {
              if (response.data.code === 0) {
                this.$router.go(0); // 刷新页面
              }
            })
            .catch(error => {
              console.log(error);
            });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }, handleSubmit() {
      if (this.dialogMode === 'new') {
        console.log('new', this.formModel);
        this.dialogVisible = false;
        axios.post('/resource/server-config/add', this.formModel)
            .then(response => {
              if (response.data.code === 0) {
                this.$router.go(0); // 刷新页面
              }
            })
            .catch(error => {
              console.log(error);
            });
      } else if (this.dialogMode === 'edit') {
        console.log('edit', this.formModel);
        this.dialogVisible = false;
        axios.post('/resource/server-config/update', this.formModel)
            .then(response => {
              if (response.data.code === 0) {
                this.$router.go(0); // 刷新页面
              }
            })
            .catch(error => {
              console.log(error);
            });
      }
    }, handleCancel() {
      this.dialogVisible = false;
    }, handleTableSelectionChange(selection) {
      this.tableSelection = selection;
    }, handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.handleSearch({});
    }, handleCurrentChange(val) {
      this.currentPage = val;
      this.handleSearch({});
    },
  }
}
</script>
<style>
.page-curd__action-bar {
  margin: 20px 0px;
}

.page-curd__table {
  margin-bottom: 20px;
}

.page-curd .el-icon-user-solid {
  padding-right: 10px;
}

.page-curd__pagination {
  text-align: right;
}
</style>